package com.juku2024.juku.viewmodel

import android.util.SparseArray
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.juku2024.juku.R
import com.juku2024.juku.base.BaseApplication
import com.juku2024.juku.db.NoteRoomUtils
import com.juku2024.juku.model.*
import com.juku2024.juku.network.api.Api
import com.juku2024.juku.network.retrofit.OnRetrofitResultListener
import com.juku2024.juku.network.retrofit.RetrofitUtils
import com.juku2024.juku.request.CategoryContentRequest
import com.juku2024.juku.request.CategoryTagRequest
import com.juku2024.juku.tools.AppUtils
import com.juku2024.juku.tools.MD5Utils
import kotlinx.coroutines.launch

class CategoryViewModel : BaseViewModel() {

    private val tagListLiveData = MutableLiveData<SparseArray<CategorySearchModel>>()
    private val searchResultsLiveData = MutableLiveData<HashMap<String, CategorySearchResultModel.AlbumResponse>>()
    val CATEGORY_CATEGORY = 1



    fun getGenreList(success: (model: ArrayList<Genre>) -> Unit, fail: (msg: String) -> Unit){
        viewModelScope.launch {
            try {
                val dao = NoteRoomUtils.getInstance().homeTabDao()
                val  homeModel = dao.query()
                // 移除推荐分类
                val genres = homeModel?.genres?.filter { it.genre_id != 0 } as ArrayList<Genre>?
                if (genres == null) {
                    fail(AppUtils.getString(R.string.empty_list))
                } else {
                    success(genres)
                }
            } catch (e: Exception) {
                e.printStackTrace()
                fail(AppUtils.getString(R.string.empty_list))
            }
        }
    }

    fun getSearchTagList(genreId: Int, success: (model: CategorySearchModel) -> Unit, fail: (msg: String) -> Unit) {
        doBaseHttp({
            var result: CategorySearchModel? = null
            if (tagListLiveData.value != null) {
                result = tagListLiveData.value?.get(genreId, null)
                if (result == null || result.classes.isNullOrEmpty() || result.tags.isNullOrEmpty() || result.years.isNullOrEmpty()) {
                    result = null
                } else {
                    success(result)
                }
            } else {
                tagListLiveData.value = SparseArray()
            }
            return@doBaseHttp result
        }, {
            // 查当前数据表是否有数据
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(genreId, appId, getAppKey(), timestamp, getExtra())
            val request = CategoryTagRequest(genreId, appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getSearchTag(genreId, getCommonRequest(request))
        }, object : OnRetrofitResultListener<CategorySearchModel> {
            override fun onSuccess(t: CategorySearchModel) {
                if (t.data.isNullOrEmpty()) {
                    if (isNotActive()) return
                    fail(AppUtils.getString(R.string.error_net))
                    return
                }
                if (isNotActive()) return

                t.data.forEach { searchTag ->
                    val targetList = ArrayList<CategorySearchTagModel>()
                    // 全部标签
                    val allTag = CategorySearchTagModel()
                    allTag.name = searchTag.name
                    allTag.id = searchTag.id
                    // 添加全部标签
                    targetList.add(allTag)
                    searchTag.data.forEach { item ->
                        val tag = CategorySearchTagModel()
                        tag.name = item.name
                        tag.id = item.id
                        targetList.add(tag)
                    }
                    if (searchTag.classes == CATEGORY_CATEGORY) { // 分类标签
                        t.tags = targetList
                    } else {
                        t.years = targetList
                    }
                }
                t.data = null
                tagListLiveData.value?.put(genreId, t)
                success(t)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }
        })
    }


    /**
     * 查询搜索结果内容
     */
    fun getCategoryList(
        genreId: Int, tagId: Int, yearId: Int, page: Int,
        success: (t: CategorySearchResultModel.AlbumResponse) -> Unit, fail: (msg: String) -> Unit
    ) {
        // 取消之前的请求
        val keyWord = StringBuilder()
        keyWord.append(genreId)
        keyWord.append("_")
        keyWord.append(tagId)
        keyWord.append("_")
        keyWord.append(yearId)
        keyWord.append("_")
        keyWord.append(page)
        val realKey = keyWord.toString()
        doBaseHttp({
            var result: CategorySearchResultModel.AlbumResponse? = null
            if (searchResultsLiveData.value != null) {
                result = searchResultsLiveData.value?.get(realKey)
                if (result != null) {
                    if (isNotActive()) return@doBaseHttp null
                    success(result)
                }
            } else {
                searchResultsLiveData.value = java.util.HashMap()
            }
            return@doBaseHttp result
        }, {
            val appId = getAppId()
            val timestamp = getSecondTimestamp()
            val sign = MD5Utils.getMD5String(genreId, tagId, yearId, page, 12, appId, getAppKey(), timestamp, getExtra())
            val request = CategoryContentRequest(genreId, tagId, yearId, page, 12, appId, timestamp, sign)
            return@doBaseHttp RetrofitUtils.instance.getApi(Api::class.java).getCategoryList(genreId, getCommonRequest(request))
        }, object : OnRetrofitResultListener<CategorySearchResultModel> {
            override fun onSuccess(t: CategorySearchResultModel) {
                if (t.album == null) {
                    if (isNotActive()) return
                    fail(AppUtils.getString(R.string.error_net))
                    return
                }
                if (isNotActive()) return
                searchResultsLiveData.value?.put(realKey, t.album)
                success(t.album)
            }

            override fun onFailed(msg: String) {
                if (isNotActive()) return
                fail(msg)
            }
        })
    }

}